package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.properties.WeChatProperties;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;


import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {
    @Autowired
    private WebSocketServer webSocketServer;
    @Autowired
    private AddressBookMapper addressBookMapper;

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;
    @Autowired
    private UserMapper userMapper;


    /**
     * 提交订单
     * @param ordersSubmitDTO
     * @return
     */
    @Override
    public OrderSubmitVO sumbit(OrdersSubmitDTO ordersSubmitDTO) {
        //异常情况的处理(收货地址为空，购物车为空)
        AddressBook addressBook=new AddressBook();
        addressBook.setId(ordersSubmitDTO.getAddressBookId());
        addressBook = addressBookMapper.getAddress(addressBook);
        if(addressBook==null)
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);

        //查询当前用户的购物车数据
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.showShoppingCart(0L);
        if(shoppingCartList==null||shoppingCartList.size()==0)
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);

        //订单新增
        Orders orders=new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO,orders);
        orders.setOrderTime(LocalDateTime.now());
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        orders.setPhone(addressBook.getPhone());
        orders.setConsignee(addressBook.getConsignee());
        orders.setAddress(addressBook.getDetail());
        orders.setPayStatus(orders.UN_PAID);
        orders.setUserId(addressBook.getUserId());
        orderMapper.insert(orders);

        //订单详细表
        List<OrderDetail>orderDetailList=new ArrayList<>();
        for (ShoppingCart shoppingCart : shoppingCartList) {
            OrderDetail orderDetail=new OrderDetail();
            BeanUtils.copyProperties(shoppingCart,orderDetail);
            orderDetail.setOrderId(orders.getId());
            orderDetailList.add(orderDetail);
        }

        //向订单详细表插入多条数据
        orderDetailMapper.insertBatch(orderDetailList);

        //清空购物车
        shoppingCartMapper.deleteShoppingCart(0L);

        OrderSubmitVO orderSubmitVO=OrderSubmitVO.builder()
                .orderAmount(orders.getAmount())
                .orderTime(orders.getOrderTime())
                .orderNumber(orders.getNumber())
                .build();

        return orderSubmitVO;
    }


    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id

        User user = userMapper.getById(0L);

       /* //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }
*/
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", "ORDERPAID");
        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        //为替代微信支付成功后的数据库订单状态更新，多定义一个方法进行修改
        Integer OrderPaidStatus = Orders.PAID; //支付状态，已支付
        Integer OrderStatus = Orders.TO_BE_CONFIRMED;  //订单状态，待接单

        //发现没有将支付时间 check_out属性赋值，所以在这里更新
        LocalDateTime check_out_time = LocalDateTime.now();

        //获取订单号码
        String orderNumber = ordersPaymentDTO.getOrderNumber();

        log.info("调用updateStatus，用于替换微信支付更新数据库状态的问题");
        orderMapper.updateStatus(OrderStatus, OrderPaidStatus, check_out_time, orderNumber);


        Orders orders = orderMapper.getByNumber(orderNumber);

        Map map=new HashMap();
        map.put("type",1);//消息类型，1表示来单提醒
        map.put("orderId",orders.getId());
        map.put("content","订单号:"+orders.getNumber());

        //通过websocket实现来单提醒，向客户端浏览器推送信息
        webSocketServer.sendToAllClient(JSON.toJSONString(map));

        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {

        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);
    }

    /**
     * 历史订单查询
     * @param page
     * @param pageSize
     * @param status
     * @return
     */
    @Override
    public PageResult pageQuery(int page, int pageSize, Integer status) {
        PageHelper.startPage(page,pageSize);

        OrdersPageQueryDTO ordersPageQueryDTO=new OrdersPageQueryDTO();
        ordersPageQueryDTO.setStatus(status);

        Page<Orders> orders = orderMapper.pageQuery(ordersPageQueryDTO);
        
        List<OrderVO>list=new ArrayList<>();
        if(orders!=null&&orders.size()>0) {
            for (Orders order : orders) {
                List<OrderDetail> orderDetailList = orderDetailMapper.getorderDetailByOrderId(order.getId());

                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(order, orderVO);
                orderVO.setOrderDetailList(orderDetailList);
                list.add(orderVO);
            }
        }

        return new PageResult(orders.getTotal(),list);
    }


    /**
     * 查询订单详情
     * @param id
     * @return
     */
    @Override
    public OrderVO getOrderDetail(Long id) {
        //根据订单id获取订单
        Orders orders = orderMapper.getById(id);

        //根据订单id获取订单详情集合
        List<OrderDetail> orderDetailList = orderDetailMapper.getorderDetailByOrderId(id);

        //将订单及订单详情封装到OrderVO中
        OrderVO orderVO=new OrderVO();
        BeanUtils.copyProperties(orders,orderVO);
        orderVO.setOrderDetailList(orderDetailList);

        return orderVO;
    }

    /**
     * 取消订单
     * @param id
     */
    @Override
    public void cancelOrder(Long id) {
        //通过订单id获取订单
        Orders orders = orderMapper.getById(id);

        //校验订单是否存在
        if (orders==null)
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);

        Integer status = orders.getStatus();

        //订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消
        if(status>2)
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);

        //订单处于未接单情况下，需要退款
        if(status.equals(Orders.TO_BE_CONFIRMED)){
            orders.setPayStatus(Orders.REFUND);
        }

        orders.setCancelTime(LocalDateTime.now());
        orders.setCancelReason("用户取消");
        orders.setStatus(Orders.CANCELLED);
        orderMapper.update(orders);
    }


    /**
     * 再来一单
     * @param id
     */
    @Override
    public void repetitionOrder(Long id) {
        //通过订单id获取订单详情
        List<OrderDetail> orderDetailList = orderDetailMapper.getorderDetailByOrderId(id);
        //获取订单通过订单id
        Orders orders = orderMapper.getById(id);
        //获取userId
        Long userId = orders.getUserId();

        //把订单详情表的内容赋值给购物车
        List<ShoppingCart> shoppingCartList = orderDetailList.stream().map(x -> {
            ShoppingCart shoppingCart = new ShoppingCart();
            BeanUtils.copyProperties(x, shoppingCart, "id");
            shoppingCart.setUserId(userId);
            shoppingCart.setCreateTime(LocalDateTime.now());
            return shoppingCart;
        }).collect(Collectors.toList());

        //将购物车对象批量添加到数据库
        shoppingCartMapper.insertBatch(shoppingCartList);
    }

    /**
     * 订单搜索
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult conditionSearch(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());

        Page<Orders> orders = orderMapper.pageQuery(ordersPageQueryDTO);

        //将订单详情(菜品信息，数量)封装到orderVO中
        List<OrderVO> list=getOrderVOList(orders);

        return new PageResult(orders.getTotal(),list);
    }

    /**
     * 各个状态的订单数量统计
     */
    @Override
    public OrderStatisticsVO statistics() {
        //根据状态分别查询待接单，待接单，代送中
        Integer toBeConfirmed = orderMapper.countStatus(Orders.TO_BE_CONFIRMED);
        Integer confirmed = orderMapper.countStatus(Orders.CONFIRMED);
        Integer deliveryInProgress = orderMapper.countStatus(Orders.DELIVERY_IN_PROGRESS);

        //封装统计对象
        OrderStatisticsVO orderStatisticsVO=new OrderStatisticsVO();
        orderStatisticsVO.setConfirmed(confirmed);
        orderStatisticsVO.setToBeConfirmed(toBeConfirmed);
        orderStatisticsVO.setDeliveryInProgress(deliveryInProgress);
        return orderStatisticsVO;
    }

    /**
     * 接单
     * @param ordersConfirmDTO
     */
    @Override
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
        Orders orders=Orders.builder()
                .status(Orders.CONFIRMED)
                .id(ordersConfirmDTO.getId())
                .build();

        orderMapper.update(orders);
    }

    /**
     * 拒单
     * @param ordersRejectionDTO
     */
    @Override
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) {
        Long orderId = ordersRejectionDTO.getId();
        Orders orders = orderMapper.getById(orderId);

        //先判断订单状态是否为待接单
        Integer status = orders.getStatus();
        if(orders==null||!orders.getStatus().equals(Orders.TO_BE_CONFIRMED))
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);

        Integer payStatus = orders.getPayStatus();
        if(payStatus==Orders.PAID)
            log.info("申请退款:{}",orderId);

        //拒单需要退款，根据订单id更新订单状态，拒单原因，取消时间
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelReason(ordersRejectionDTO.getRejectionReason());
        orders.setCancelTime(LocalDateTime.now());

        orderMapper.update(orders);
    }

    /**
     * 客户端取消订单
     * @param ordersCancelDTO
     */
    @Override
    public void adminCancelOrder(OrdersCancelDTO ordersCancelDTO) {
        //获取订单
        Long userId = ordersCancelDTO.getId();
        Orders orders = orderMapper.getById(userId);

        Integer status = orders.getStatus();
        //处于待付款，已接单，派送中才能进行取消操作
        if(orders == null ||status.equals(Orders.TO_BE_CONFIRMED)||status.equals(Orders.COMPLETED )||status.equals(Orders.CANCELLED))
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);

        Integer payStatus = orders.getPayStatus();
        if(payStatus.equals(Orders.PAID))
            log.info("申请退款：{}",userId);

        orders.setCancelTime(LocalDateTime.now());
        orders.setCancelReason(ordersCancelDTO.getCancelReason());
        orders.setPayStatus(Orders.REFUND);
        orders.setStatus(Orders.CANCELLED);

        orderMapper.update(orders);

    }

    /**
     * 派送订单
     * @param id
     */
    @Override
    public void delivery(Long id) {
        //获取订单
        Orders orders = orderMapper.getById(id);

        Integer status = orders.getStatus();
        //判断订单状态是否合法
        if(orders == null ||!status.equals(Orders.CONFIRMED))
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);

        orders.setStatus(Orders.DELIVERY_IN_PROGRESS);
        orderMapper.update(orders);
    }

    /**
     * 完成订单
     * @param id
     */
    @Override
    public void complete(Long id) {
        //获取订单
        Orders orders = orderMapper.getById(id);

        Integer status = orders.getStatus();
        //判断订单状态是否合法
        if(status==null||!status.equals(Orders.DELIVERY_IN_PROGRESS))
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);

        orders.setStatus(Orders.COMPLETED);
        orderMapper.update(orders);
    }

    /**
     * 催单
     * @param id
     */
    @Override
    public void reminder(Long id) {
        //查询订单是否存在
        Orders orders=orderMapper.getById(id);

        if(orders==null)
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);

        //基于WebSocket实现催单
        Map map=new HashMap<>();
        map.put("type",2);
        map.put("orderId",id);
        map.put("content","订单号:"+orders.getNumber());

        webSocketServer.sendToAllClient(JSON.toJSONString(map));
    }


    private List<OrderVO> getOrderVOList(Page<Orders> orders) {
        List<OrderVO> orderVOlist=new ArrayList<>();

        List<Orders> ordersList = orders.getResult();

        if(!CollectionUtils.isEmpty(ordersList)){
            for (Orders o : ordersList) {
                OrderVO orderVO=new OrderVO();
                BeanUtils.copyProperties(o,orderVO);

                //获取订单信息字符串
                String orderDishesStr=getOrderDetailStr(o.getId());
                //将订单信息(菜品信息，数量)封装到orderVO中
                orderVO.setOrderDishes(orderDishesStr);
                orderVOlist.add(orderVO);
            }
        }
        return orderVOlist;
    }

    private String getOrderDetailStr(Long orderId) {
        List<OrderDetail> orderDetailList = orderDetailMapper.getorderDetailByOrderId(orderId);

        List<String> orderDishList = orderDetailList.stream().map(odl -> {
            String orderDetailStr = odl.getName() + "*" + odl.getNumber();
            return orderDetailStr;
        }).collect(Collectors.toList());

        return String.join("",orderDishList);

    }
}
